import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../common/api/index.dart';
import '../../common/models/index.dart';
import '../../common/routers/index.dart';
import '../../common/services/index.dart';
import '../../common/utils/index.dart';
import '../../common/widgets/index.dart';
import '../../environment_config.dart';
import '../../global.dart';
import '../common/inner_webview/index.dart';
import 'state.dart';

class SplashController extends GetxController {
  SplashController();

  final state = SplashState();
  Uint8List? launchLogo;

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    O2UI.hideStatusBar();
    state.copyright =
        '@ ${DateTime.now().year} ${'appName'.tr} All right reserved.';
    _checkPrivacyAgree();
    super.onReady();
  }

  @override
  void onClose() {
    O2UI.showStatusBar();
    super.onClose();
  }
  /// 是否同意了隐私政策
  void _checkPrivacyAgree() {
    if (Platform.isAndroid && !EnvironmentConfig.isDirectConnectMode()) {
      final isAgree = SharedPreferenceService.to
          .getBool(SharedPreferenceService.isAgreePrivacyKey);
      if (isAgree) {
        _splashLoading();
      } else {
        _privacyDialog();
      }
    } else {
      _splashLoading();
    }
  }

  /// 隐私政策 弹出窗口
  void _privacyDialog() async {
    final context = Get.context;
    if (context == null) {
      OLogger.i('没有 context，退出 APP');
      exit(0);
    }
    RichText richText = RichText(
      text: TextSpan(
          text: 'privacy_policy_dialog_content_part1'.tr,
          style: Theme.of(context).textTheme.bodyMedium,
          children: [
            TextSpan(
                text: 'user_agreement_book_mark'.tr,
                style: TextStyle(
                    color: Theme.of(context).colorScheme.primary,
                    fontSize: 14.sp),
                recognizer: TapGestureRecognizer()
                  ..onTap = () => openUserAgreement()),
            TextSpan(
              text: 'privacy_policy_dialog_content_part2'.tr,
              style: Theme.of(context).textTheme.bodyMedium,
            ),
            TextSpan(
                text: 'privacy_policy_book_mark'.tr,
                style: TextStyle(
                    color: Theme.of(context).colorScheme.primary,
                    fontSize: 14.sp),
                recognizer: TapGestureRecognizer()
                  ..onTap = () => openPrivacyPolicy()),
            TextSpan(
              text: 'privacy_policy_dialog_content_part3'.tr,
              style: Theme.of(context).textTheme.bodyMedium,
            ),
          ]),
    );
    final result = await O2UI.showCustomDialog(
        context, 'privacy_policy_dialog_title'.tr, richText,
        positiveBtnText: 'agree'.tr, cancelBtnText: 'disagree'.tr);
    if (result != null && result == O2DialogAction.positive) {
      _agree();
      _splashLoading();
    } else {
      // 退出
      OLogger.i('不同意，退出 APP');
      exit(0);
    }
  }

  /// 写入标记
  void _agree() {
    SharedPreferenceService.to.putBool(SharedPreferenceService.isAgreePrivacyKey, true);
  }

  void openUserAgreement() {
    InnerWebviewPage.open('https://www.o2oa.net/userService.html');
  }

  void openPrivacyPolicy() {
    InnerWebviewPage.open('https://www.o2oa.net/secret.html');
  }

  void _denyRoot() {
    final context = Get.context;
    if (context == null) {
      OLogger.i('没有 context，退出 APP');
      exit(0);
    }
    O2UI.showAlert(context, 'deny_root'.tr, okPressed: () => exit(0));
  }

  /// 启动加载过程
  void _splashLoading() async {
    // 安全检查
    final result = await O2FlutterMethodChannelUtils().checkRootNative();
    if (result) {
      _denyRoot();
      return;
    }
    Global.initLater(); // 需要同意后执行的
    // 演示版本  app
    if (EnvironmentConfig.isDemoApp()) {
      // 获取演示服务器列表
      await SampleEditionManger.instance.loadServerListFromWwwService();
      await SampleEditionManger.instance.setCurrentAndReloadApp(SampleEditionManger.instance.getCurrent(), needReload: false);
    } else {
      // 检查绑定服务器和服务器信息
      var hasUnitInfo = await O2ApiManager.instance.loadO2UnitFromSP();
      if (!hasUnitInfo) {
        // 没有服务器信息 去绑定
        OLogger.i('splash_nobind_go'.tr);
        state.tips = 'splash_nobind_go'.tr;
        Get.offNamed(O2OARoutes.bind);
        return;
      }
    }
    // 开始连接 O2OA  服务器
    state.tips = 'splash_connecting'.tr;
    // 连接服务器
    try {
      OLogger.d('开始连接O2OA服务器。。。。。');
      var isLoadO2OA = await ProgramCenterService.to.loadCenterServerOnline();
      if (!isLoadO2OA) {
        _connectServerFail();
      } else {
        state.tips = 'splash_logining'.tr;
        try {
          await ProgramCenterService.to.loadCurrentStyle(); // 获取appstyle
          state.showLaunchLogo = true; // 显示 logo
          // 读取设备号
          if (GetPlatform.isMobile) {
            O2ApiManager.instance.getJPushDeviceIdRemote();
          }
        } catch (err, stackTrace) {
          OLogger.e('获取appStyle失败', err, stackTrace);
        }
        // 登录判断
        _checkLogin().then((isLogin) {
          OLogger.d('登录： $isLogin');
          if (isLogin) {
            Get.offNamed(O2OARoutes.home);
          } else {
            // 清除保存的用户信息
            O2ApiManager.instance.cleanUser();
            _goToLogin();
          }
        });
      }
    } catch (err, stackTrace) {
      OLogger.e('连接服务器失败', err, stackTrace);
      _connectServerFail();
    }
  }

  /// 显示连接错误信息
  void _connectServerFail() {
    OLogger.i('splash_connect_fail'.tr);
    state.tips = 'splash_connect_fail'.tr;
    O2UI.showConfirm(Get.context, 'connect_o2_server_fail_go_to_sample'.tr,
        okText: 'sample_server_name'.tr, okPressed: () {
      O2ApiManager.instance.putSampleUnitServerAndReload();
    }, cancelPressed: () => exit(0),);
  }

  /// 检测是否有登录信息 并获取用户最新登录信息
  Future<bool> _checkLogin() async {
    O2Person? userJson = O2ApiManager.instance.loadUserFromSP();
    if (userJson == null) {
      return false;
    } else {
      try {
        O2Person? person = await OrgAuthenticationService.to.who();
        if (person == null || person.token == null || person.token!.isEmpty) {
          return false;
        } else {
          // 更新用户信息
          await O2ApiManager.instance.setupUser(person);
          return true;
        }
      } catch (err, stackTrace) {
        OLogger.e('检查用户登录情况失败', err, stackTrace);
        return false;
      }
    }
  }

  /// 去登录
  void _goToLogin() {
    if (EnvironmentConfig.o2AppIsDemo) {
      Get.offNamed(O2OARoutes.demoLogin);
    } else {
      Get.offNamed(O2OARoutes.login);
    }
  }
}
